package com.zhu.library_management_system.controller;

import com.zhu.library_management_system.pojo.BookBorrowing;
import com.zhu.library_management_system.pojo.User;
import com.zhu.library_management_system.responseMessage.ResponseMessage;
import com.zhu.library_management_system.jwt.TokenService;
import com.zhu.library_management_system.service.UserService;
import com.zhu.library_management_system.util.RoleVerify;
import com.zhu.library_management_system.util.VerifyLoginUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public ResponseMessage<?> login(@RequestBody User user){
        User user1 = userService.login(user.getName(), user.getPassword());
        if (user1 == null || !user1.getPassword().equals(user.getPassword())){
            return ResponseMessage.success(500, "用户名或密码错误",null);
        }
        String token = TokenService.generateToken(user1.getUserId());
        return ResponseMessage.success(200, "登录成功", token);
    }

    @PostMapping("/logout")
    @ApiOperation("用户登出")
    public ResponseMessage<?> logout(@RequestHeader("Authorization") String token){
        Integer userId = VerifyLoginUtil.verifyLogin(token);
        if (userId == null){
            return ResponseMessage.success(401, "Token无效或已过期", null);
        }
        String rawToken = token.replace("Bearer ", "");
        // 将Token加入黑名单，有效期设为当前时间（立即失效）
        VerifyLoginUtil.releaseToken(rawToken, 0);
        return ResponseMessage.success(200, "登出成功", null);
    }

    @PostMapping("/register")
    @ApiOperation("用户注册")
    public ResponseMessage<User> register(@RequestBody User user){
        if (userService.register(user.getName()) != null){
            return ResponseMessage.success(500, "用户名已存在", null);
        }
        userService.UserAdd(user);
        return ResponseMessage.success(200, "注册成功！", user);
    }

    @GetMapping("/userAll")
    @ApiOperation("查询所有用户")
    public ResponseMessage<List<User>> User(@RequestHeader("Authorization") String token){
        Integer loginId = VerifyLoginUtil.verifyLogin(token);
        if (loginId == null || VerifyLoginUtil.isTokenValid(token)){
            return ResponseMessage.success(401, "Token无效或已过期", null);
        }
        if (RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(null) || !RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(0)){
            return ResponseMessage.success(403, "抱歉，你无权进行此操作！", null);
        }
        Iterable<User> user = userService.SelectUserAll();
        List<User> userList =  StreamSupport.stream(user.spliterator(), false)
                .collect(Collectors.toList());
        return ResponseMessage.success(userList);
    }

    @GetMapping("/selectUser/{userId}")
    @ApiOperation("查询单个用户")
    public ResponseMessage<User> User(@RequestHeader("Authorization") String token, @PathVariable Integer userId){
        Integer loginId = VerifyLoginUtil.verifyLogin(token);
        if (loginId == null || VerifyLoginUtil.isTokenValid(token)){
           return ResponseMessage.success(401, "Token无效或已过期", null);
        }

        if (RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(null) || !RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(0)){
            return ResponseMessage.success(403, "抱歉，你无权进行此操作！", null);
        }

        try {
            User user = userService.SelectUser(userId);
            return ResponseMessage.success(user);
        }catch (RuntimeException e){
            return ResponseMessage.success(404, e.getMessage(), null);
        }
    }

    @PostMapping("/addUser")
    @ApiOperation("添加用户")
    public ResponseMessage<User> UserAdd(@RequestHeader("Authorization") String token,@Valid @RequestBody User user){
        Integer loginId = VerifyLoginUtil.verifyLogin(token);
        if (loginId == null || VerifyLoginUtil.isTokenValid(token)){
           return ResponseMessage.success(401, "Token无效或已过期", null);
        }

        if (RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(null) || !RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(0)){
            return ResponseMessage.success(403, "抱歉，你无权进行此操作！", null);
        }

        userService.UserAdd(user);
        return ResponseMessage.success(user);
    }

    @DeleteMapping("/deleteUser/{userId}")
    @ApiOperation("删除用户")
    public ResponseMessage<User> UserDelete(@RequestHeader("Authorization") String token, @PathVariable Integer userId){
        Integer loginId = VerifyLoginUtil.verifyLogin(token);
        if (loginId == null || VerifyLoginUtil.isTokenValid(token)){
          return ResponseMessage.success(401, "Token无效或已过期", null);
        }

        if (RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(null) || !RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(0)){
            return ResponseMessage.success(403, "抱歉，你无权进行此操作！", null);
        }

        userService.UserDelete(userId);
        return ResponseMessage.success(null);
    }

    @PutMapping("/updateUser/{userId}")
    @ApiOperation("修改用户")
    public ResponseMessage<User> UserUpdate(@RequestHeader("Authorization") String token, @PathVariable Integer userId,@Valid @RequestBody User user){
        Integer loginId = VerifyLoginUtil.verifyLogin(token);
        if (loginId == null || VerifyLoginUtil.isTokenValid(token)){
           return ResponseMessage.success(401, "Token无效或已过期", null);
        }

        if (RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(null) || !RoleVerify.verifyRole(userService.getRole(loginId).getRole()).equals(0)){
            return ResponseMessage.success(403, "抱歉，你无权进行此操作！", null);
        }

        user.setUserId(userId);
        userService.UserUpdate(user);
        return ResponseMessage.success(user);
    }
}
